import serial
import threading
import time

# RS485设备配置
RS485_0_DEVICE = "/dev/ttyCH9344USB0"
RS485_1_DEVICE = "/dev/ttyCH9344USB1"
BAUD_RATE = 115200

# 发送数据配置
RS485_0_SEND_DATA = b"000"
RS485_1_SEND_DATA = b"111"
SEND_INTERVAL = 0.5  # 发送间隔（秒）
RECV_INTERVAL = 0.1  # 接收间隔（秒）

# 创建串口对象
ser0 = serial.Serial(RS485_0_DEVICE, BAUD_RATE, timeout=1)
ser1 = serial.Serial(RS485_1_DEVICE, BAUD_RATE, timeout=1)

# 线程运行标志
running = True

def sender():
    """发送线程函数"""
    while running:
        try:
            # RS485_0 发送数据
            ser0.write(RS485_0_SEND_DATA)
            print(f"RS485_0 发送: {RS485_0_SEND_DATA.decode()}")
            time.sleep(SEND_INTERVAL)  # 短暂延迟
            
            # RS485_1 发送数据
            ser1.write(RS485_1_SEND_DATA)
            print(f"RS485_1 发送: {RS485_1_SEND_DATA.decode()}")
            time.sleep(SEND_INTERVAL)  # 短暂延迟
            
        except Exception as e:
            print(f"发送错误: {e}")
            break

def receiver():
    """接收线程函数"""
    while running:
        try:
            # RS485_1 接收数据
            if ser1.in_waiting > 0:
                data1 = ser1.read(ser1.in_waiting)
                if data1:
                    print(f"RS485_1 接收: {data1.decode().strip()}")
            
            # RS485_0 接收数据
            if ser0.in_waiting > 0:
                data0 = ser0.read(ser0.in_waiting)
                if data0:
                    print(f"RS485_0 接收: {data0.decode().strip()}")
            
            time.sleep(RECV_INTERVAL)  # 短暂延迟以减少CPU使用
            
        except Exception as e:
            print(f"接收错误: {e}")
            break

if __name__ == "__main__":
    print("RS485通信测试开始 (按Ctrl+C停止)")
    
    # 创建并启动线程
    send_thread = threading.Thread(target=sender)
    recv_thread = threading.Thread(target=receiver)
    
    send_thread.start()
    recv_thread.start()
    
    try:
        # 主线程等待
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n程序被用户中断")
        running = False
        
        # 等待线程结束
        send_thread.join()
        recv_thread.join()
        
        # 关闭串口
        ser0.close()
        ser1.close()
        
        print("串口已关闭，程序退出")